const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 7096 });

// 存储所有连接的客户端
const clients = new Set();

server.on('connection', (ws) => {
    console.log('New client connected');
    clients.add(ws);

    ws.on('message', (data) => {
        // 确保转成字符串
        const message = data.toString('utf8');
        for (const client of clients) {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                console.log('received:', message);
                client.send(message); // 发送字符串
            }
        }
    });

    ws.on('close', () => {
        console.log('Client disconnected');
        clients.delete(ws);
    });

    ws.on('error', (error) => {
        console.error('WebSocket error:', error);
    });

    ws.send(JSON.stringify({text:'Welcome to WebSocket server!'}));
});

console.log('WebSocket server running at ws://localhost:7096');